<template>
  <view class="ad-banner-container" v-if="show">
    <!-- 微信小程序横幅广告 -->
    <!-- #ifdef MP-WEIXIN -->
    <ad
      :unit-id="currentAdUnitId"
      ad-type="banner"
      ad-theme="white"
      @load="onAdLoad"
      @error="onAdError"
    ></ad>
    <!-- #endif -->

    <!-- H5 端广告占位 -->
    <!-- #ifdef H5 -->
    <view class="ad-placeholder">
      <text class="ad-label">广告</text>
    </view>
    <!-- #endif -->
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from "vue";
import {
  showBannerAd,
  hideBannerAd,
  destroyBannerAd,
} from "@/utils/ad-manager";
import { useAdStore } from "@/stores/ad";

const props = defineProps({
  adUnitId: {
    type: String,
    default: "",
  },
  position: {
    type: String,
    default: "bottom", // top, bottom
  },
});

const adStore = useAdStore();
const show = ref(true);

const currentAdUnitId = computed(() => {
  return props.adUnitId || adStore.adConfig.banner;
});

onMounted(() => {
  const adConfig = adStore.adConfig;
  const unitId = props.adUnitId || adConfig.banner;

  if (unitId) {
    showBannerAd({
      adUnitId: unitId,
      position: props.position,
    });
  }
});

onUnmounted(() => {
  hideBannerAd();
  destroyBannerAd();
});

function onAdLoad() {
  console.log("横幅广告加载成功");
  adStore.recordAdShow("banner");
}

function onAdError(err) {
  console.error("横幅广告加载失败:", err);
  show.value = false;
}
</script>

<style scoped>
.ad-banner-container {
  width: 100%;
  background-color: #fff;
}

.ad-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200rpx;
  background-color: #f5f5f5;
  border: 1rpx dashed #ddd;
}

.ad-label {
  font-size: 28rpx;
  color: #999;
}
</style>
